<script lang="ts" setup>
import { useForm } from '@/hooks/web/useForm'
import { FormSchema } from '@/types/form'
import * as CourseApi from '@/api/course'
import { CourseCreateDTO } from '@/api/course'

const message = useMessage()
const { t } = useI18n()

const dialogVisible = ref(false)
const dialogTitle = ref('新增课程')
const formLoading = ref(false)
const formType = ref<'create' | 'update'>('create')

const schema = reactive<FormSchema[]>([
  {
    field: 'courseName',
    label: '课程名称',
    value: '',
    component: 'Input',
    formItemProps: {
      rules: [{ required: true, message: '请输入课程名称' }]
    }
  },
  {
    field: 'courseCoverUrl',
    label: '课程封面',
    value: '',
    component: 'UploadImg',
    formItemProps: {
      rules: [{ required: true, message: '请上传课程封面' }]
    }
  },
  {
    field: 'carType',
    label: '车辆类型',
    value: '客车',
    component: 'Select',
    componentProps: {
      options: [
        { label: '客车', value: '客车' },
        { label: '货车', value: '货车' },
        { label: '小车', value: '小车' },
        { label: '摩托车', value: '摩托车' },
        { label: '房车', value: '房车' },
        { label: '新手驾驶', value: '新手驾驶' }
      ]
    },
    formItemProps: {
      rules: [{ required: true, message: '请选择课程状态' }]
    }
  },
  {
    field: 'spuStatus',
    label: '上架状态',
    value: 1,
    component: 'Select',
    componentProps: {
      options: [
        { label: '上架', value: 1 },
        { label: '下架', value: 2 }
      ]
    },
    formItemProps: {
      rules: [{ required: true, message: '请选择课程状态' }]
    }
  },
  {
    field: 'isRecommend',
    label: '是否推荐',
    value: false,
    component: 'Switch'
  },
  {
    field: 'validDays',
    label: '有效天数',
    value: 365,
    component: 'InputNumber'
  },
  {
    field: 'spuVirtualSalesCount',
    label: '虚拟销量',
    value: 0,
    component: 'InputNumber'
  },
  {
    field: 'skuPrice',
    label: '课程价格(元)',
    value: 0,
    component: 'InputNumber'
  },
  {
    field: 'sortNo',
    label: '排序',
    value: 0,
    component: 'InputNumber'
  },
  {
    field: 'courseDetail',
    label: '课程详情',
    value: '',
    component: 'Editor',
    formItemProps: {
      rules: [{ required: true, message: '请输入课程详情' }]
    }
  }
])

const { register, elFormRef, methods: formMethods } = useForm()

const open = (type: 'create' | 'update', id?: string) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'update' ? '编辑课程' : '新增课程'
  formType.value = type

  if (type === 'update') {
    formLoading.value = true
    CourseApi.get(id!).then((data) => {
      data.skuPrice = data.skuPrice / 100
      console.log('update: ', data)
      formMethods.setValues(data)
      formLoading.value = false
    })
  }
}
defineExpose({ open })

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!elFormRef.value) return
  const valid = await elFormRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true

  try {
    const formData = (await formMethods.getFormData()) || {}

    if (formType.value === 'create') {
      // 转换表单
      const data: CourseCreateDTO = {
        ...(formData as any),
        spuInfo: {
          id: formData.spuId || undefined,
          status: formData.spuStatus as number,
          virtualSalesCount: formData.spuVirtualSalesCount as number
        },
        skuInfo: { id: formData.skuId, price: formData.skuPrice * 100 }
      }
      ;['spuStatus', 'spuVirtualSalesCount', 'skuPrice'].forEach((key) => delete data[key])

      console.log('创建课程：', data)
      await CourseApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      // 转换表单
      const data: CourseApi.CourseUpdateDTO = {
        ...(formData as any),
        spuInfo: {
          id: formData.spuId || undefined,
          status: formData.spuStatus as number,
          virtualSalesCount: formData.spuVirtualSalesCount as number
        },
        skuInfo: { id: formData.skuId, price: formData.skuPrice * 100 }
      }
      ;['spuStatus', 'spuVirtualSalesCount', 'skuPrice'].forEach((key) => delete data[key])

      console.log('更新课程：', data)
      await CourseApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>

<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="700">
    <Form :schema="schema" @register="register" />
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
